<template>
    <el-card class="box-card"  style="border-right: none; border-bottom: none !important; border-top: none !important;border-radius: 0;">
        <div class="card-header">
            <span>会员管理</span>
        </div>
        <el-form :inline="true" :model="formInline" class="form-inline">
            <el-form-item label="用户名">
                <el-input v-model="formInline.username" placeholder="用户名" clearable />
            </el-form-item>
            <el-form-item label="VIP">
              <el-select
                v-model="formInline.vip"
                placeholder="VIP"
                clearable
              >
                <el-option v-for="item in vipAllList" :label="item.name" :value="item.id" />
              </el-select>
            </el-form-item>
            <el-form-item label="状态">
                <el-select
                v-model="formInline.state"
                placeholder="状态"
                clearable
                >
                <el-option label="全部" value="" />
                <el-option label="启用" value="1" />
                <el-option label="禁用" value="0" />
                </el-select>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" @click="onSubmit">搜索</el-button>
                <el-button @click="resetForm">重置</el-button>
            </el-form-item>
        </el-form>

        <el-table 
        :data="userList" 
        height="600px" 
        style="width: 100%" 
        :vip="vipList" 
        v-loading="loading"
        row-key="id"
        lazy
        :default-expand-all="false"
        :load="(row, treeNode, resolve) => {
          // 只允许加载第一级的子节点（即只显示两级）
          if (!row._level) {
            // 第一层，加载子节点
            loadChildren({ ...row, _level: 1 }, treeNode, (children) => {
              // 给子节点标记_level为2
              children.forEach(child => child._level = 2);
              resolve(children);
            });
          } else {
            // 第二层及以后不再加载
            resolve([]);
          }
        }"
        :tree-props="{ children: 'children', hasChildren: 'junior_count' }"
        >
          <!-- 渲染用户名 -->
            <el-table-column prop="username" label="用户名" min-width="150" />
            <!-- 渲染昵称 -->
            <el-table-column prop="nickname" label="昵称" min-width="150" />

            <el-table-column label="推荐人" min-width="150">
              <template #default="scope">
                {{ scope.row.manager?.username || '无' }}
              </template>
            </el-table-column>
           
            <!-- 渲染头像 -->
            <el-table-column label="头像" min-width="150">
            <template #default="scope">
                <img :src="scope.row.avatar" alt="头像" style="width: 50px; height: 50px; border-radius: 50%;" />
            </template>
            </el-table-column>

            <el-table-column prop="vip.name" label="VIP" min-width="150" />
            <!-- 性别 -->
            <el-table-column prop="sex_text" label="性别" min-width="150" />
            <el-table-column label="余额" min-width="150">
              <template #default="scope">
              <el-tex
                @click="moneyEdit(scope.$index, scope.row)"
                 class="hover-pointer"
              >
                {{ scope.row.money }}
              </el-tex>
              </template>
            </el-table-column>
            

            <!-- 渲染手机号 -->
            <el-table-column prop="phone" label="手机号" min-width="150" />

            <!-- 渲染状态 -->
            <el-table-column label="状态" min-width="100">
              <template #default="scope">
                  <el-tag v-if="scope.row.status === 1" type="success">{{scope.row.status_text}}</el-tag>
                  <el-tag v-else type="danger">{{scope.row.status_text}}</el-tag>
              </template>
            </el-table-column>

            <!-- 渲染创建时间 -->
            <el-table-column prop="created_at" label="创建时间" width="160" />

            <!-- 渲染更新时间 -->
            <el-table-column prop="updated_at" label="更新时间" width="160" />

            <!-- 操作 -->
            <el-table-column fixed="right" label="操作" width="200" >
            <template #default="scope">
                <el-button size="small" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
                <el-button size="small" type="danger" @click="handleDelete(scope.row)">删除</el-button>
                <el-button size="small" @click="handleView(scope.$index, scope.row)">查看</el-button>
            </template>
            </el-table-column>
        </el-table>
        <el-pagination class="el-p"
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[10, 20, 50, 100]"
        :small="small"
        :disabled="disabled"
        :background="background"
        layout="total, sizes, prev, pager, next"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        />
    </el-card>

    <!-- 编辑管理员对话框 -->
  <el-dialog
    v-model="dialogVisible"
    :title="编辑会员"
    width="500px"
    :close-on-click-modal="false"
  >
    <EditMemberForm ref="addFormRef" :form-data="currentFormData" :is-edit="dialogType === 'edit'" :vipList="vipList"/>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitForm">确定</el-button>
      </span>
    </template>
  </el-dialog>
  <!-- 编辑钱包 -->
  <el-dialog
      v-model="moneyDialogVisible"
      title="编辑钱包"
      width="300px"
      :close-on-click-modal="false"
    >
      <EditUserMoney ref="moneyFormRef" :formData="currentFormData" is-edit="edit" :typeList="typeList" />
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="moneyDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitMoneyForm">确定</el-button>
        </span>
      </template>
  </el-dialog>

  <el-drawer
    v-model="drawerVisible"
    title="会员详情"
    direction="rtl"
    size="50%"
  >
    <el-descriptions :column="1" border>
      <el-descriptions-item label="用户名">{{ currentFormData?.username }}</el-descriptions-item>
      <el-descriptions-item label="昵称">{{ currentFormData?.nickname }}</el-descriptions-item>
      <el-descriptions-item label="手机号">{{ currentFormData?.phone }}</el-descriptions-item>
      <el-descriptions-item label="VIP">{{ currentFormData?.vip?.name ?? '未绑定' }}</el-descriptions-item>
      <el-descriptions-item label="余额">{{ currentFormData?.money }}</el-descriptions-item>
      <el-descriptions-item label="状态">
        <el-tag :type="currentFormData?.status === 1 ? 'success' : 'danger'">
          {{ currentFormData?.status === 1 ? '启用' : '禁用' }}
        </el-tag>
      </el-descriptions-item>
      <el-descriptions-item label="创建时间">{{ currentFormData?.created_at }}</el-descriptions-item>
      <el-descriptions-item label="更新时间">{{ currentFormData?.updated_at }}</el-descriptions-item>
    </el-descriptions>
  </el-drawer>
</template>
<script setup>
import { ref,reactive,watch } from 'vue';
import { memberService } from '@/api/memberService';
import { userMoneyService } from '@/api/userMoneyService';
import { ElMessage, ElMessageBox } from 'element-plus';
import { vipService } from '@/api/vipService';
import EditMemberForm from '@/components/EditMemberForm.vue';
import EditUserMoney from '@/components/EditUserMoney.vue';
const currentPage = ref(1)  // 默认第一页
const pageSize = ref(10)    // 默认每页10条
const small = ref(false)
const background = ref(false)
const disabled = ref(false)
const dialogVisible = ref(false);
const moneyDialogVisible = ref(false);
const total = ref(0);
const dialogType = ref('add');
const currentFormData = ref(null);
const addFormRef = ref(null);
const moneyFormRef = ref(null);
const drawerVisible = ref(false);
const loading = ref(true); // 加载状态
const vipList = ref();
const vipAllList = ref();

const formInline = reactive({
    username: '',
    state: '',
    vip:''
});
const userList = ref([]);
const typeList = reactive({});

//查看分类列表 启用未删除的数据
const getVipList =  async () => {
  vipService.getAllList({status:1}).then(res => {
        vipList.value = res;
    });
}
//查看所有分类列表 包括软删除的数据
const getVipAllList =  async () => {
  vipService.getAllList().then(res => {
    vipAllList.value = res;
  });
}

const getTypeText = async () => {
    const response = await userMoneyService.getTypeText();
    typeList.value=response || {};
};

getTypeText();

getVipList();
getVipAllList();

// 获取用户列表数据
const fetchUserList = async () => {
    loading.value = true;
    try {
      const params = {
        username: formInline.username,
        status: formInline.state,
        vip: formInline.vip,
        page: currentPage.value,
        pageSize: pageSize.value
      };
      const response = await memberService.getList(params);
      userList.value = response.data || [];
      total.value = response.total || 0;
    } catch (error) {
      ElMessage.error('获取用户列表失败');
      userList.value = [];
      total.value = 0;
    }finally {
      loading.value = false; // 停止加载状态
    }
};

fetchUserList();

const onSubmit = () => {
    fetchUserList();
};
const resetForm = () => {
    formInline.username = '';
    formInline.state = '';
};

const handleSizeChange = (val) => {
    pageSize.value = val;
    fetchUserList();
};
const handleCurrentChange = (val) => {
    currentPage.value = val;
    fetchUserList();
};
// 监听对话框关闭事件
watch(dialogVisible, (newVal) => {
    if (!newVal) {
      resetDialog();
    }
});

// 重置对话框状态
const resetDialog = () => {
    currentFormData.value = null;
    if (addFormRef.value) {
      addFormRef.value.resetForm();
    }
};

/**
* 处理删除管理员的操作
* @param {Object} row - 包含管理员信息的对象，用于标识要删除的管理员
*/
const handleDelete = async (row) => {
    try {
      // 弹出确认对话框，询问用户是否确定要删除指定的管理员
      await ElMessageBox.confirm(
        `确定要删除会员 ${row.username} 吗？`,
        '警告',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }
      );

      // 调用后端接口删除指定ID的管理员
      await memberService.del(row.id);
      ElMessage.success('删除成功');
      // 重新获取用户列表数据
      fetchUserList();
    } catch (error) {
      // 处理删除过程中可能出现的错误
      // if (error !== 'cancel') {
      //   // 如果用户没有取消操作，则显示删除失败的错误提示
      //   ElMessage.error('删除失败');
      // }
    }
};

const handleEdit = (index, row) => {
    dialogType.value = 'edit';
    currentFormData.value = { ...row };
    dialogVisible.value = true;
};

const moneyEdit = (index, row)=>{

    currentFormData.value = { ...row };
    moneyDialogVisible.value = true;
}

const submitMoneyForm = async ()=>{
  // 检查表单引用是否存在
  if (!moneyFormRef.value) return;

    // 验证表单数据合法性
    const isValid = await moneyFormRef.value.validateForm();
    // 如果表单数据不合法，则终止操作
    if (!isValid) return;

    try {
        // 复制表单数据
        const formData = { ...moneyFormRef.value.form };
        // 更新管理员信息
        await memberService.updateMemberMoney(formData.id,formData).then(() => {
            // 处理更新操作成功的情况
            ElMessage.success('编辑成功');
            // 关闭对话框
            moneyDialogVisible.value = false;
            // 刷新用户列表
            fetchUserList();
        });

    } catch (error) {
      // 处理添加或更新操作失败的情况
      //ElMessage.error(dialogType.value === 'add' ? '新增管理员失败' : '更新管理员失败');
    }
}

const submitForm = async () => {
    // 检查表单引用是否存在
    if (!addFormRef.value) return;

    // 验证表单数据合法性
    const isValid = await addFormRef.value.validateForm();
    // 如果表单数据不合法，则终止操作
    if (!isValid) return;

    try {
        // 复制表单数据
        const formData = { ...addFormRef.value.form };
        // 更新管理员信息
        await memberService.updateMember(formData.id,formData).then(() => {
            // 处理更新操作成功的情况
            ElMessage.success('会员更新成功');
            // 关闭对话框
            dialogVisible.value = false;
            // 刷新用户列表
            fetchUserList();
        });

    } catch (error) {
      // 处理添加或更新操作失败的情况
      //ElMessage.error(dialogType.value === 'add' ? '新增管理员失败' : '更新管理员失败');
    }
  };
  const handleView = (index, row) => {
    currentFormData.value = { ...row };
    drawerVisible.value = true;
  };
  
const loadChildren = async (row, treeNode, resolve) => {
    try {
        const children = await memberService.getChildren(row.id);
        console.log('获取子节点数据:', children.data.data);
        resolve(children.data.data || []); // 解析子节点数据
    } catch (error) {
        console.error('Failed to load children:', error);
        resolve([]); // Resolve with an empty array to prevent hanging
    }
};
</script>
<style scoped>
.form-inline {
    margin: 20px 0;
    border-bottom: 1px solid #e4e7ed;
}
.el-p{
    margin-top: 15px;
    display: flex;
    justify-self: flex-end;
}
.el-select{
    width: 85px;
}
.card-header{
    display: flex;
    justify-content: space-between;
    align-items: center;
    height: 50px;
    border-bottom: 1px solid #e4e7ed;
}
.hover-pointer{
  cursor: pointer;
}
</style>
